package by.dkusch.aircompany.webapp.page.main;

import org.apache.wicket.Application;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.util.string.Strings;

import by.dkusch.aircompany.webapp.app.BasicAuthenticationSession;
import by.dkusch.aircompany.webapp.page.base.BaseLayout;
import by.dkusch.aircompany.webapp.page.base.panels.LanguagePanel;

import com.googlecode.wicket.kendo.ui.panel.KendoFeedbackPanel;

public class LoginPage extends BaseLayout {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static final String ID_FORM = "form";
	public static final String ID_PASSWORD = "password";
	public static final String ID_USERNAME = "username";

	private String username;
	private String password;

	@Override
	protected void onInitialize() {
		super.onInitialize();

		this.add(new KendoFeedbackPanel("feedback"));

		// if already logged then should not see login page at all
		if (AuthenticatedWebSession.get().isSignedIn()) {
			setResponsePage(Application.get().getHomePage());
		}
		final Form<Void> form = new Form<Void>(ID_FORM) {

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit() {
				if (Strings.isEmpty(username) || Strings.isEmpty(password)) {
					return;
				}
				final boolean authResult = AuthenticatedWebSession.get().signIn(username, password);
				if (authResult) {
					// continueToOriginalDestination();
					setResponsePage(Application.get().getHomePage());
				} else {
					if (BasicAuthenticationSession.get().isUserArc()) {
						error(getString("authentication.error.archive"));
					} else {
						error(getString("authentication.error"));
					}
				}
			}
		};

		form.setDefaultModel(new CompoundPropertyModel<LoginPage>(this));
		form.add(new RequiredTextField<String>(ID_USERNAME));
		form.add(new PasswordTextField(ID_PASSWORD));
		add(new LanguagePanel("languagePanel"));
		add(form);
		getMenuPanel().setVisible(false);
		getFooterPanel().setVisible(false);
		getHeaderPanel().setVisible(false);


	}

	@Override
	protected IModel<String> getPageTitle() {
		return new ResourceModel("p.login.title");
	}

}
